<template>
  <div id="whole">
    <!-- <div style="width:100px;height:100px;background-color:black;" @click="test"></div> -->
    <!-- {{this.soilWK}} -->
    <!-- {{this.search_WK_resp}} -->
    <!-- {{this.box2_table}} -->
    <!-- {{this.echart_data.source}} -->
    <!-- {{this.search_options.county}} -->
    <!-- {{this.select_one}} -->
    <!-- {{this.search_bar_req}} -->
    <!-- {{this.box3_table}} -->
    <!-- {{this.echart_data_pie.source}} -->
    <div id="container" style="width: 100%; height: 100%; position: relative" >
        <el-tooltip placement="bottom" content="柱状图">
            <div class="option_buttons" style="top:25%;right:2%;"  @click="box1_open" >
                <div style="height: 45px; width: 45px;align-content:center;text-align:center;">
                    <i class="iconfont ali-tubiao" style="font-size:40px"></i>
                </div>
            </div>
        </el-tooltip>
        <el-tooltip placement="bottom" content="区县统计表">
            <div class="option_buttons" style="top:55%;right:2%;"  @click="box2_open" >
                <div style="height: 45px; width: 45px;align-content:center;text-align:center;">
                    <img src="../../public/table.png" style="height:30px;">
                </div>
            </div>
        </el-tooltip>
        <el-tooltip placement="bottom" content="类型饼图">
            <div class="option_buttons" style="top:40%;right:2%;"  @click="box3_open" >
                <div style="height: 45px; width: 45px;align-content:center;text-align:center;">
                    <i class="iconfont ali-bingtu" style="font-size:30px"></i>
                </div>
            </div>
        </el-tooltip>
        <div v-show="box3_show" class="WK_search_box" ref="box3">
            <div style="width:1000px;height:30px;">
                <div style="background-color:#959da9;align-content:center;position:relative;height:100%;">
                    <i class="el-icon-search" style="margin-left:5px;"></i>
                    <span style="color:white;margin-left:5px;">数据分析-饼图</span>
                    <div class="el-icon-close" style="margin-left:300px;position:absolute;right:3%;" @click="box3_show=false;"></div>
                </div>
                <div style="width:100%;">
                    <div style="width:100%;height:80px;">
                        <el-form :model="search_req">
                            <el-row style="padding-top:20px">
                                <el-col :span="12">
                                    <el-form-item label="切换统计因子" label-width="180px">
                                        <el-select v-model="search_req.type" size="mini" style="width:180px;">
                                            <el-option
                                            v-for="item in search_options.type"
                                            :key="item.label"
                                            :label="item.label"
                                            :value="item.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </div>
                <div style="width:100%;">
                    <div ref="chart_pie" style="width:1000px;height:490px;"></div>
                </div>
            </div>
        </div>
        <div v-if="box2_show" class="WK_search_box" style="background-color:white;display:flex;flex-direction:column">
            <div style="flex:0 0 6%;background-color:#959da9;align-content:center;position:relative;;">
                <i class="el-icon-search" style="margin-left:5px;"></i>
                <span style="color:white;margin-left:5px;">土壤专题-空间分布-统计表</span>
                <div class="el-icon-close" style="margin-left:300px;position:absolute;right:3%;" @click="box2_show=false;"></div>
            </div>
            <div>
                <el-table :data="box2_table" max-height="560px">
                        <el-table-column
                            prop="id"
                            fixed
                            label="序号"
                            width="80">
                        </el-table-column>
                        <el-table-column
                            prop="county"
                            fixed
                            label="区县"
                            width="80">
                        </el-table-column>
                        <el-table-column
                            prop="c"
                            label="黄壤面积(km^2)"
                            width="140">
                        </el-table-column>
                        <el-table-column
                            prop="d"
                            label="黄棕壤面积(km^2)"
                            width="90">
                        </el-table-column>
                        <el-table-column
                            prop="m"
                            label="石灰(岩)土面积(km^2)"
                            width="110">
                        </el-table-column>
                        <el-table-column
                            prop="n"
                            label="紫色土面积(km^2)"
                            width="100">
                        </el-table-column>
                        <el-table-column
                            prop="q"
                            label="山地草甸土面积(km^2) "
                            width="110">
                        </el-table-column>
                        <el-table-column
                            prop="u"
                            label="水稻土面积(km^2)"
                            width="100">
                        </el-table-column>
                        <el-table-column
                            prop="f"
                            label="棕谏面积(km^2)"
                            width="100">
                        </el-table-column>
                        <el-table-column
                            prop="o"
                            label="粗骨土面积(km^2)"
                            width="100">
                        </el-table-column>
                        <el-table-column
                            prop="e"
                            label="黄褐土面积(km^2)"
                            width="100">
                        </el-table-column>
                        <el-table-column
                            prop="k"
                            label="新积土面积(km^2)"
                            width="100">
                        </el-table-column>
                </el-table>
            </div>
        </div>
        <div v-show="box1_show" class="WK_search_box" ref="box1">
            <div style="width:1000px;height:30px;">
                <div style="background-color:#959da9;align-content:center;position:relative;height:100%;">
                    <i class="el-icon-search" style="margin-left:5px;"></i>
                    <span style="color:white;margin-left:5px;">数据分析-柱状图</span>
                    <div class="el-icon-close" style="margin-left:300px;position:absolute;right:3%;" @click="box1_show=false;"></div>
                </div>
                <div style="width:100%;">
                    <div style="width:100%;height:80px;">
                        <el-form :model="search_bar_req">
                            <el-row style="padding-top:20px">
                                <el-col :span="12">
                                    <el-form-item label="切换区县" label-width="180px">
                                        <el-select v-model="search_bar_req.county" size="mini" style="width:180px;">
                                            <el-option
                                            v-for="item in search_options.county"
                                            :key="item.label"
                                            :label="item.label"
                                            :value="item.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </div>
                <div style="width:100%;">
                    <div ref="chart_bar" style="width:1000px;height:490px;"></div>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {treeList} from '@/assets/common'

import Axios from '@/my_axios';

import {Map, View} from 'ol';
import {fromLonLat} from 'ol/proj';

import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector'


import XYZ from 'ol/source/XYZ';
import VectorSource from 'ol/source/Vector';

import GeoJSON from 'ol/format/GeoJSON';
import {Style, Fill, Stroke} from 'ol/style';
import { Polygon } from 'ol/geom';

export default {
    name: "mapVue",
    mounted() {
        this.initAMap();

        // this.$nextTick(()=> {
        // })


        // box2_table
        Axios.post("/getsoil_spatialtable", {
            search_req: this.search_bar_req
        })
        .then((resp)=> {
            // console.log('.....', resp);
            this.box2_table = resp.data.data;
        })

        // box3_table
        Axios.post("/getsoil_byType", {
            search_req: this.search_req
        })
        .then((resp)=> {
            // console.log(resp)
            this.box3_table = resp.data.data;
        })

        const excludedCounties = ["巴东县", "秭归县", "兴山县", "宜昌市区"];
        treeList.children.forEach(tmp => {
            // console.log(tmp)
            if (!excludedCounties.includes(tmp.label)) {
                this.search_options.county.push({
                    label: tmp.label,
                    value: tmp.label
                });
            }
        });

    },
    unmounted() {
        this.map?.destroy();
    },
    data: function () {
        return {

            // details_box
            box1_show:false,
            box1_table:[],

            // box2
            box2_show:false,
            box2_table:[],

            // box3
            box3_show:false,
            box3_table:[],
            echart_data_pie: [],

            // search_WK
            search_WK_req:{
                'title':'tr',
            },

            //chart_bar
            select_one:null,
            myChart:null,
            echart_data:{
                x_data:["product"],
                source:[],
            },
            search_options: {
                county:[
                    {
                        label: '全部',
                        value: 'ALL'
                    }
                ],
                type: [
                    {
                        label: '容重',
                        value: 'bulk'
                    },
                    {
                        label: '湿度',
                        value: 'humidity'
                    },
                    {
                        label: 'PH值',
                        value: 'ph'
                    },
                    {
                        label: '有机质',
                        value: 'som'
                    },
                    {
                        label: '可用磷',
                        value: 'available_p'
                    },
                    {
                        label: '可用氮',
                        value: 'available_n'
                    },
                    {
                        label: '氢含量',
                        value: 'h'
                    },
                    {
                        label: '硫含量',
                        value: 's'
                    },
                ]
            },
            search_bar_req: {
                'county': 'ALL'
            },
            // echart_pie
            search_req: {
                'type': 'bulk'
            },
        };
    },
    watch: {
        search_req: {
            handler(){
                Axios.post("/getsoil_byType", {
                    search_req: this.search_req
                })
                .then((resp)=> {
                    console.log(resp)
                    this.box3_table = resp.data.data;
                })
                this.echart_data_pie.source = this.box3_table;
                // this.echart_data_pie.setOption()
                this.initChartPie()
            },
            deep: true
        },
        search_bar_req: {
            handler() {
                console.log('yes')
                Axios.post("/getsoil_spatialtable", {
                    search_req: this.search_bar_req
                })
                .then((resp)=> {
                    // console.log('.....', resp);
                    this.box2_table = resp.data.data;
                })
                setTimeout(() => {
                    this.echart_data.source = this.box2_table
                    if(!this.box1_show){
                        this.box1_show = true
                    }
                    this.initChart()
                }, 100);
            },
            deep: true
        }
    },
    methods: {
        initAMap() {
            var tianditu_token = '816cded7027c0dd4de266ef32a030a19'
            this.map = new Map({
                target: 'container',
                view: new View({
                    projection: 'EPSG:3857',
                    center: fromLonLat([109, 30]),
                    // center: fromLonLat([0, 0]),
                    zoom: 8.3,
                }),
            });
            this.dxLayer = new TileLayer({
                name: 'tianditu_dx',
                zIndex:1,
                source: new XYZ({
                    url: "http://t0.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=" + tianditu_token,
                    wrapX: false
                })
            }),
            this.map.addLayer(this.dxLayer);

            this.dxmLayer = new TileLayer({
                name: 'tianditu_dxm',
                zIndex:5,
                source: new XYZ({
                    url: "http://t0.tianditu.com/DataServer?T=cta_w&x={x}&y={y}&l={z}&tk=" + tianditu_token,
                    wrapX: false
                })
            }),
            this.map.addLayer(this.dxmLayer);

            this.qxLayer = new VectorLayer({
                name: 'qx',
                zIndex:4,
                opacity:0.7,
                source: new VectorSource({
                    url: '/geoDatas/trAnalyse_qx.json',
                    format: new GeoJSON(),
                }),
                style: this.getDefaultStyle,
            });
            this.map.addLayer(this.qxLayer);

            this.trLayer = new VectorLayer({
                name: 'river',
                zIndex:3,
                source: new VectorSource({
                    url: '/geoDatas/tr.json',
                    format: new GeoJSON(),
                }),
                style: new Style({
                    stroke: new Stroke({
                        color:'blue',
                        width: 2 // 边缘宽度
                    }),
                    fill: new Fill({
                        color: 'rgba(255, 255, 255, 0.6)' // 填充颜色，可根据需要调整
                    })
                })
            });
            this.map.addLayer(this.trLayer);

            // 点击事件
            this.map.on('click', (e)=> {
                // console.log("点击事件：", e.coordinate)
                const feature = this.map.forEachFeatureAtPixel(e.pixel, (feature)=> {
                    return feature;
                })
                if(feature && feature.getGeometry() instanceof Polygon) {
                    // console.log("点击了:", feature.getKeys());
                    // console.log("点击了:", feature.get('index'), feature);//tmd, 必须为get才能取到; 然后就可以用this.GeoWK来取得对应WK的详细数据
                    this.select_one = feature.get('NAME99')
                    this.qxLayer.setStyle(this.getDefaultStyle)

                    // let index = feature.get('index');
                    this.search_bar_req.county = this.select_one
                }
            })

        },
        //chart
        initChart() {
            // 基于准备好的dom，初始化echarts实例

            // 指定图表的配置项和数据
            var option = {
                legend: {},
                tooltip: {},
                table_req:{
                    qx: '',
                    factor: ''
                },
                dataset: {
                    dimensions: ['county', "c", "d", "m", "n", "q", "u", "f", "o", "e", "k"],
                    source: this.echart_data.source
                    // source:[
                    //     {
                    //         county:"江津区",
                    //         c:10,
                    //         d:20,
                    //         f:30,
                    //     }
                    // ]
                },
                xAxis: { type: 'category' },
                yAxis: {},
                // Declare several bar series, each will be mapped
                // to a column of dataset.source by default.
                series:[ 
                    { name: '黄壤', type: 'bar', encode: { x: 'county', y: 'c' } },
                    { name: '黄棕壤', type: 'bar', encode: { x: 'county', y: 'd' } },
                    { name: '石灰(岩)土', type: 'bar', encode: { x: 'county', y: 'm' } },
                    { name: '紫色土', type: 'bar', encode: { x: 'county', y: 'n' } },
                    { name: '山地草甸土', type: 'bar', encode: { x: 'county', y: 'q' } },
                    { name: '水稻土', type: 'bar', encode: { x: 'county', y: 'u' } },
                    { name: '棕壤', type: 'bar', encode: { x: 'county', y: 'f' } },
                    { name: '粗骨土', type: 'bar', encode: { x: 'county', y: 'o' } },
                    { name: '黄褐土', type: 'bar', encode: { x: 'county', y: 'e' } },
                    { name: '新积土', type: 'bar', encode: { x: 'county', y: 'k' } }
                ]
            };

            this.$nextTick(()=> {
                this.myChart = echarts.init(this.$refs.chart_bar);
                this.myChart.setOption(option);
            })
        },
        initChartPie() {
            var options = {
                legend: {},
                label:{
                    formatter: '{b}({d}%)'
                },
                series: [
                    {
                        type: 'pie',
                        stillShowZeroSum: false,
                        data: this.echart_data_pie.source
                    }
                ]
            }
            this.$nextTick(()=> {
                this.myChart_pie = echarts.init(this.$refs.chart_pie);
                this.myChart_pie.setOption(options);
            })
        },
        // 其他方法
        test() {
            console.log("*****test********");
            this.dzLayer.getSource().clear();

        },
        getDefaultStyle(feature){
            const name = feature.get('NAME99');

            const isHightlighted = (name === this.select_one);
            // console.log('--------------------------------', isHightlighted)
            return new Style({
                fill: new Fill({
                    color: isHightlighted? 'rgba(255, 0, 0, 0.6)' : 'rgba(58, 175, 205, 0.8)'
                }),
                stroke: new Stroke({
                    color: 'black',
                    width: 1
                })
            })
        },
        // 传入位置（地理坐标or城市编号），然后将当前地图中心聚焦于此地并设置合适的缩放比例
        focus_on(location, done) {
            // console.log('!!!!!!!!!!!!!', location)
            var view = this.map.getView()
            location = fromLonLat(location)
            // tmp.setCenter(fromLonLat(center));
            // https://openlayers.org/en/latest/examples/animation.html
            const duration = 2000;
            const zoom = view.getZoom();
            let parts = 2;
            let called = false;
            function callback(complete) {
                --parts;
                if (called) {
                return;
                }
                if (parts === 0 || !complete) {
                called = true;
                done(complete);
                }
            }
            view.animate(
                {
                center: location,
                duration: duration,
                },
                callback,
            );
            view.animate(
                {
                zoom: zoom - 1,
                duration: duration / 2,
                },
                {
                zoom: zoom,
                duration: duration / 2,
                },
                callback,
            );
        },
        navi_click(data) {
            this.select_one = data.label;
            this.qxLayer.setStyle(this.getDefaultStyle);
            //focus_on
            this.focus_on(data.lng, function(){})
        },
        box1_open() {
            // complete the echart datas
            // for x
            if(this.echart_data.x_data.length===1){
                this.box2_table.forEach(element => {
                    this.echart_data.x_data.push(element.county);
                });
            }
            this.echart_data.source = this.box2_table;

            if(!this.myChart)
                this.initChart();

            this.box1_show = this.box1_show?false:true;
        },
        box3_open() {
            // complete the echart datas
            // for x
            this.echart_data_pie.source = this.box3_table;

            if(!this.myChart_pie)
                this.initChartPie();

            this.box3_show = this.box3_show?false:true;
        },
        search_WK_ok() {
            Axios.post('/search_WK', {
                search_WK_req:this.search_WK_req
            }).then((resp)=> {
                console.log('resp:', resp)
            })
        },
        search_WK_reset() {
            this.search_WK_req = {"title":'dz'};
            this.search_WK_resp = [];
        },
        box2_open() {
            // console.log('enter')
            this.box2_show = this.box2_show?false:true;
        },
    },
};
</script>

<style scoped>
.box_column {
    flex: 0 0 14%;
    /* border: 1px solid black; */
    align-content: center;
    text-align: center;
}
.title_choice {
    width:160px;
    height: 60px;
    margin:3px;
    background-color: green;
    align-content: center;
    /* color:white; */
    /* background-image: url('../../public/turang.jpeg'); */
}
.title_choice /deep/ .el-radio__label {
    color: white;
}

.option_buttons {
    position: absolute;
    z-index: 10;
    background-color: white;
    border: 2px solid grey;
}

.option_buttons:hover{
    background-color: orange;
}

.WK_search_box {
    width:1000px;
    height: 600px;
    z-index:11;
    background-color:white;
    position:absolute;
    top:5%;
    left:20%;
    box-shadow: 5px 5px 15px rgba(0, 0, 0.5);
    border: 2px solid #999;
}

::v-deep .el-descriptions {
    width:100%;
}
</style>
